const { promisify } = require('util')
const path = require('path')
const download = promisify(require('download-git-repo'))

const { selectRepo } = require('../config/repo-config')

const { commandSpawn } = require('../utils/terminal')

const { Inquirer } = require('../utils/inquirer')

const spinner = require('../utils/spinner')

const { compile, writeToFile } = require('../utils/utils')

const createProjectAction = async (project) => {
  // 先让用户选择项目模板
  Inquirer().then(async ({ template }) => {
    // log.success('aw-cli help you create your project...')
    spinner.success('aw-cli help you create your project...')
    // 1. clone 项目
    await download(selectRepo(template), project, { clone: true })
    spinner.success('clone finish to await install')
    // 2. 执行npm install
    spinner.start('npm install...')
    let command = process.platform === 'win32' ? 'npm.cmd' : 'npm'
    await commandSpawn(command, ['install'], { cwd: `./${project}` })
    // log.success('install finish~')
    spinner.finish('install finish')
  })

  // 小程序模板是不需要运行的。
  // 3. 运行npm run serve
  // await commandSpawn(command, ['run', 'serve'], { cwd: `./${project}` })
  // 4. 打开浏览器(此操作也可以在项目模板中配置)
  // 需要安装open插件
  // open("http://localhost:8000/")
}

// 添加组件的action、
const addComponentAction = async (name, dest) => {
  // 1. 编译ejs模块 result
  // compile(name, dest)
  let result = await compile('vue-component.ejs', { name, lowerName: name.toLowerCase() })
  // 2. 写入文件的操作（编译cjs模板生成result，将result写入vue文件中）
  const targetPath = path.resolve(dest, `${name}.vue`)
  writeToFile(targetPath, result)
  // 3. 放到对应的文件夹
}

module.exports = { createProjectAction, addComponentAction }
